import React, { useState, useEffect, useCallback } from 'react';
import { Card, Button, Space, message, Modal, Tag, Row, Col, Typography, Spin } from 'antd';
import {
    PlusOutlined,
    EditOutlined,
    DeleteOutlined,
    ClockCircleOutlined,
    HolderOutlined,
    CalendarOutlined,
    FieldTimeOutlined,
    OrderedListOutlined
} from '@ant-design/icons';
import { stepService } from '../../services/stepService';
import StepForm from './StepForm';
import dayjs from 'dayjs';
import { DndContext, closestCenter, KeyboardSensor, PointerSensor, useSensor, useSensors } from '@dnd-kit/core';
import { SortableContext, verticalListSortingStrategy, useSortable } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import styled from 'styled-components';

const { Text, Paragraph } = Typography;

// 创建一个样式化的步骤卡片
const StepCard = styled(Card)`
    margin-bottom: 12px;
    border-radius: 6px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);

    .ant-card-head {
        padding: 0 12px;
        min-height: 36px;
        border-bottom: 1px solid #f0f0f0;
    }

    .ant-card-body {
        padding: 12px;
    }

    &:hover {
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.12);
    }
`;

// 创建一个虚框卡片用于添加新步骤
const AddStepCard = styled(Card)`
    margin-bottom: 12px;
    border-radius: 6px;
    border: 1px dashed #d9d9d9;
    background-color: #fafafa;
    cursor: pointer;
    transition: all 0.3s;

    .ant-card-body {
        padding: 16px;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    &:hover {
        border-color: #1890ff;
        color: #1890ff;
    }
`;

// 拖拽手柄样式
const DragHandle = styled.div`
    cursor: move;
    color: #999;
    margin-right: 8px;
    display: flex;
    align-items: center;

    &:hover {
        color: #1890ff;
    }
`;

// 顺序编号样式
const OrderBadge = styled.div`
    display: flex;
    align-items: center;
    justify-content: center;
    width: 28px;
    height: 28px;
    background-color: #f0f0f0;
    color: #666;
    border-radius: 50%;
    font-weight: bold;
    margin-right: 10px;
    flex-shrink: 0;
`;

// 可排序的步骤卡片组件
const SortableStepCard = ({ step, onEdit, onDelete, onStatusChange }) => {
    const {
        attributes,
        listeners,
        setNodeRef,
        transform,
        transition
    } = useSortable({ id: step.id });

    const style = {
        transform: CSS.Transform.toString(transform),
        transition
    };

    // 确定当前状态
    let status;
    if (step.isCompleted) {
        status = 'COMPLETED';
    } else if (step.actualStartDate) {
        status = 'IN_PROGRESS';
    } else {
        if (step.updatedAt && !step.actualEndDate) {
            const createdTime = new Date(step.createdAt).getTime();
            const updatedTime = new Date(step.updatedAt).getTime();

            if (updatedTime > createdTime) {
                status = 'IN_PROGRESS';
            } else {
                status = 'TODO';
            }
        } else {
            status = 'TODO';
        }
    }

    const getStatusColor = (status) => {
        const colors = {
            'TODO': 'default',
            'IN_PROGRESS': 'processing',
            'COMPLETED': 'success'
        };
        return colors[status] || 'default';
    };

    const getStatusText = (status) => {
        const texts = {
            'TODO': '待开始',
            'IN_PROGRESS': '进行中',
            'COMPLETED': '已完成'
        };
        return texts[status] || '待开始';
    };

    return (
        <div ref={setNodeRef} style={style}>
            <StepCard
                title={
                    <div style={{ display: 'flex', alignItems: 'center' }}>
                        <DragHandle {...attributes} {...listeners}>
                            <HolderOutlined />
                        </DragHandle>
                        <OrderBadge>{step.orderNum}</OrderBadge>
                        <Text strong ellipsis style={{ flex: 1 }}>{step.title}</Text>
                    </div>
                }
                extra={
                    <Space size="small">
                        <Tag
                            color={getStatusColor(status)}
                            style={{ cursor: 'pointer', margin: 0 }}
                            onClick={() => {
                                // 循环切换状态
                                let nextStatus;
                                if (status === 'TODO') {
                                    nextStatus = 'IN_PROGRESS';
                                } else if (status === 'IN_PROGRESS') {
                                    nextStatus = 'COMPLETED';
                                } else {
                                    nextStatus = 'TODO';
                                }

                                // 转换为后端需要的 isCompleted
                                const isCompleted = nextStatus === 'COMPLETED';
                                onStatusChange(step, isCompleted);
                            }}
                        >
                            {getStatusText(status)}
                        </Tag>
                        <Button
                            type="text"
                            size="small"
                            icon={<EditOutlined />}
                            onClick={() => onEdit(step)}
                        />
                        <Button
                            type="text"
                            size="small"
                            danger
                            icon={<DeleteOutlined />}
                            onClick={() => onDelete(step)}
                        />
                    </Space>
                }
            >
                {step.description && (
                    <Paragraph
                        ellipsis={{ rows: 2, expandable: true, symbol: '展开' }}
                        style={{ marginBottom: '8px' }}
                    >
                        {step.description}
                    </Paragraph>
                )}
                <Row gutter={16} style={{ fontSize: '12px', color: '#666' }}>
                    <Col span={12}>
                        <Space size="small">
                            <FieldTimeOutlined />
                            <span>预计工时: {step.estimatedHours || 0} 小时</span>
                        </Space>
                    </Col>
                    <Col span={12}>
                        <Space size="small">
                            <CalendarOutlined />
                            <span>截止日期: {step.expectedEndDate ? dayjs(step.expectedEndDate).format('YYYY-MM-DD') : '无'}</span>
                        </Space>
                    </Col>
                </Row>
            </StepCard>
        </div>
    );
};

// 自定义步骤服务实现
const customStepService = {
    // 内存中存储的临时步骤 (用于创建模式)
    _steps: [],
    _tempIdCounter: 0,

    // 生成临时ID
    _generateTempId() {
        this._tempIdCounter += 1;
        return `temp_${this._tempIdCounter}`;
    },

    // 初始化步骤列表
    initSteps(steps = []) {
        this._steps = steps.map((step, index) => ({
            ...step,
            id: step.id || this._generateTempId(),
            orderNum: step.orderNum || (index + 1)
        }));
        return this._steps;
    },

    // 获取所有步骤
    getAllSteps() {
        return [...this._steps];
    },

    // 添加步骤
    addStep(stepData) {
        const maxOrderNum = this._steps.length > 0
            ? Math.max(...this._steps.map(s => s.orderNum || 0))
            : 0;

        const newStep = {
            ...stepData,
            id: this._generateTempId(),
            orderNum: stepData.orderNum || (maxOrderNum + 1),
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString()
        };

        this._steps.push(newStep);
        return newStep;
    },

    // 更新步骤
    updateStepInMemory(id, stepData) {
        const index = this._steps.findIndex(step => step.id === id);
        if (index !== -1) {
            this._steps[index] = {
                ...this._steps[index],
                ...stepData,
                updatedAt: new Date().toISOString()
            };
            return this._steps[index];
        }
        return null;
    },

    // 删除步骤
    removeStep(id) {
        const index = this._steps.findIndex(step => step.id === id);
        if (index !== -1) {
            const removedStep = this._steps.splice(index, 1)[0];

            // 重新计算顺序号
            this._steps = this._steps.map((step, idx) => ({
                ...step,
                orderNum: idx + 1
            }));

            return removedStep;
        }
        return null;
    },

    // 批量更新步骤顺序
    updateStepsInMemory(steps) {
        this._steps = steps.map(step => ({
            ...step,
            updatedAt: new Date().toISOString()
        }));
        return this._steps;
    }
};

const StepList = ({ taskId, isCreating = false, stepService: injectedStepService = stepService }) => {
    const [steps, setSteps] = useState([]);
    const [loading, setLoading] = useState(false);
    const [modalVisible, setModalVisible] = useState(false);
    const [currentStep, setCurrentStep] = useState(null);
    const [confirmLoading, setConfirmLoading] = useState(false);

    // 确保我们有一个可用的步骤服务
    const effectiveStepService = isCreating ? customStepService : injectedStepService;

    // 传感器配置，用于拖拽排序
    const sensors = useSensors(
        useSensor(PointerSensor, {
            activationConstraint: {
                distance: 8, // 8px的移动距离才会触发拖拽，防止误触
            },
        }),
        useSensor(KeyboardSensor)
    );

    // 获取步骤列表
    const fetchSteps = useCallback(async () => {
        // 如果没有任务ID，直接返回
        if (!taskId) {
            return;
        }

        // 如果是创建新任务模式，使用内存中的步骤
        if (isCreating) {
            if (effectiveStepService.getAllSteps) {
                const tempSteps = effectiveStepService.getAllSteps();
                setSteps(tempSteps);
            } else {
                setSteps([]);
            }
            return;
        }

        // 以下是编辑或查看任务模式，需要从后端获取步骤
        setLoading(true);
        try {
            // 使用注入的服务获取步骤
            const response = await effectiveStepService.getStepsByTask(taskId);

            // 处理不同的响应格式
            let stepsData = [];

            // 检查响应格式并提取数据
            if (response && response.data) {
                if (response.data.data && Array.isArray(response.data.data)) {
                    // 如果 response.data.data 是数组
                    stepsData = response.data.data;
                } else if (Array.isArray(response.data)) {
                    // 如果 response.data 直接是数组
                    stepsData = response.data;
                }
            }

            // 确保所有步骤都属于当前任务
            const taskIdStr = String(taskId);
            stepsData = stepsData.filter(step => String(step.taskId) === taskIdStr);

            // 按顺序排序
            stepsData.sort((a, b) => (a.orderNum || 0) - (b.orderNum || 0));

            setSteps(stepsData);
        } catch (error) {
            console.error('获取步骤列表失败:', error);
            message.error('获取步骤列表失败');
        } finally {
            setLoading(false);
        }
    }, [taskId, effectiveStepService, isCreating]);

    // 处理步骤表单提交
    const handleStepFormSuccess = async (values) => {
        setConfirmLoading(true);
        try {
            let updatedStep;

            // 如果有ID，则是更新操作
            if (values.id) {
                if (isCreating) {
                    // 创建模式下，更新内存中的步骤
                    updatedStep = effectiveStepService.updateStepInMemory(values.id, values);
                } else {
                    // 正常模式，调用API更新
                    const response = await effectiveStepService.updateStep(values.id, values);
                    updatedStep = response.data?.data || response.data || values;
                    message.success('步骤更新成功');
                }

                // 更新本地步骤列表
                setSteps(prevSteps =>
                    prevSteps.map(step =>
                        step.id === values.id ? { ...step, ...updatedStep } : step
                    )
                );
            } else {
                // 创建新步骤
                // 设置默认顺序号为当前最大顺序号+1
                const maxOrderNum = steps.length > 0
                    ? Math.max(...steps.map(s => s.orderNum || 0))
                    : 0;

                const newStep = {
                    ...values,
                    taskId,
                    orderNum: maxOrderNum + 1
                };

                // 如果是创建任务模式，使用临时服务
                if (isCreating) {
                    const addedStep = effectiveStepService.addStep(newStep);
                    setSteps(prevSteps => [...prevSteps, addedStep]);
                } else {
                    // 正常创建步骤
                    const response = await effectiveStepService.createStep(taskId, newStep);
                    const createdStep = response.data?.data || response.data || newStep;
                    message.success('步骤添加成功');

                    // 添加到本地步骤列表
                    setSteps(prevSteps => [...prevSteps, createdStep]);
                }
            }

            // 关闭模态框
            setModalVisible(false);
        } catch (error) {
            console.error('保存步骤失败:', error);
            message.error('保存步骤失败');
        } finally {
            setConfirmLoading(false);
        }
    };

    // 修复后的 handleDragEnd 函数
    const handleDragEnd = async (event) => {
        const { active, over } = event;
        if (!active || !over || active.id === over.id) return;

        try {
            // 找到拖拽的步骤和目标位置
            const oldIndex = steps.findIndex(step => step.id === active.id);
            const newIndex = steps.findIndex(step => step.id === over.id);

            if (oldIndex === -1 || newIndex === -1) {
                console.error('无法找到拖拽的步骤或目标位置');
                return;
            }

            // 保存原始步骤列表，以便出错时恢复
            const originalSteps = [...steps];

            // 创建新的排序后的步骤数组
            const newSteps = [...steps];
            const [movedStep] = newSteps.splice(oldIndex, 1);
            newSteps.splice(newIndex, 0, movedStep);

            // 更新顺序号
            const updatedSteps = newSteps.map((step, index) => ({
                ...step,
                orderNum: index + 1
            }));

            // 立即更新本地状态（乐观更新）
            setSteps(updatedSteps);

            // 如果是创建模式，只需更新内存中的步骤
            if (isCreating) {
                if (effectiveStepService.updateStepsInMemory) {
                    effectiveStepService.updateStepsInMemory(updatedSteps);
                }
                return;
            }

            // 非创建模式，需要向后端更新
            const hide = message.loading('正在更新步骤顺序...', 0);
            setLoading(true);

            try {
                // 使用 Promise.all 并行处理多个更新请求
                const updatePromises = updatedSteps.map(step => {
                    // 发送完整的步骤对象，而不仅仅是 orderNum
                    return effectiveStepService.updateStep(step.id, step);
                });

                await Promise.all(updatePromises);
                hide();
                message.success('步骤顺序更新成功');
            } catch (error) {
                console.error('更新步骤顺序失败:', error);
                hide();
                message.error('更新步骤顺序失败');

                // 恢复原来的顺序
                setSteps(originalSteps);
            } finally {
                setLoading(false);
            }
        } catch (error) {
            console.error('拖拽排序处理错误:', error);
            message.error('操作失败，请重试');
        }
    };

    // 处理添加步骤
    const handleAdd = () => {
        setCurrentStep(null); // 清空当前步骤，表示新建
        setModalVisible(true);
    };

    // 处理编辑步骤
    const handleEdit = (step) => {
        setCurrentStep(step);
        setModalVisible(true);
    };

    // 处理删除步骤
    const handleDelete = (step) => {
        Modal.confirm({
            title: '确认删除',
            content: `确定要删除步骤 "${step.title}" 吗？`,
            okText: '确认',
            cancelText: '取消',
            onOk: async () => {
                try {
                    if (isCreating) {
                        // 创建模式下，直接从内存中删除
                        effectiveStepService.removeStep(step.id);
                        setSteps(prevSteps => prevSteps.filter(s => s.id !== step.id));
                    } else {
                        // 正常模式，调用API删除
                        await effectiveStepService.deleteStep(step.id);
                        message.success('步骤删除成功');
                        setSteps(prevSteps => prevSteps.filter(s => s.id !== step.id));
                    }
                } catch (error) {
                    console.error('删除步骤失败:', error);
                    message.error('删除步骤失败');
                }
            }
        });
    };

    // 处理状态变更
    const handleStatusChange = async (step, isCompleted) => {
        try {
            const updatedStep = { ...step, isCompleted };

            if (isCreating) {
                // 创建模式下，直接更新内存中的步骤
                effectiveStepService.updateStepInMemory(step.id, updatedStep);
                setSteps(prevSteps =>
                    prevSteps.map(s => s.id === step.id ? updatedStep : s)
                );
            } else {
                // 正常模式，调用API更新
                await effectiveStepService.updateStep(step.id, { isCompleted });

                // 更新本地步骤状态
                setSteps(prevSteps =>
                    prevSteps.map(s => s.id === step.id ? { ...s, isCompleted } : s)
                );
            }
        } catch (error) {
            console.error('更新步骤状态失败:', error);
            message.error('更新步骤状态失败');
        }
    };

    // 在组件挂载和taskId变化时获取步骤列表
    useEffect(() => {
        // 初始化自定义步骤服务（如果是创建模式）
        if (isCreating && effectiveStepService.initSteps) {
            effectiveStepService.initSteps([]);
        }

        fetchSteps();
    }, [taskId, fetchSteps]);

    // 渲染步骤列表
    const renderStepList = () => {
        if (loading && steps.length === 0) {
            return <div style={{ textAlign: 'center', padding: '20px' }}><Spin /></div>;
        }

        if (!steps || steps.length === 0) {
            return (
                <div style={{ textAlign: 'center', padding: '20px', color: '#999' }}>
                    <OrderedListOutlined style={{ fontSize: '24px', marginBottom: '8px' }} />
                    <p>暂无步骤</p>
                </div>
            );
        }

        // 使用DndContext提供拖拽排序功能
        return (
            <DndContext
                sensors={sensors}
                collisionDetection={closestCenter}
                onDragEnd={handleDragEnd}
            >
                <SortableContext
                    items={steps.map(step => step.id)}
                    strategy={verticalListSortingStrategy}
                >
                    {steps.map(step => (
                        <SortableStepCard
                            key={step.id}
                            step={step}
                            onEdit={handleEdit}
                            onDelete={handleDelete}
                            onStatusChange={handleStatusChange}
                        />
                    ))}
                </SortableContext>
            </DndContext>
        );
    };

    return (
        <Spin spinning={loading && steps.length > 0}>
            <div className="step-list">
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '16px' }}>
                    <h3 style={{ margin: 0 }}>任务步骤</h3>
                    <Button
                        type="primary"
                        icon={<PlusOutlined />}
                        onClick={handleAdd}
                    >
                        添加步骤
                    </Button>
                </div>

                {renderStepList()}

                {/* 添加步骤的虚线框卡片 */}
                {steps.length === 0 && !loading && (
                    <AddStepCard onClick={handleAdd}>
                        <PlusOutlined style={{ marginRight: '8px' }} />
                        <span>添加第一个步骤</span>
                    </AddStepCard>
                )}

                {/* 步骤表单模态框 */}
                <StepForm
                    visible={modalVisible}
                    confirmLoading={confirmLoading}
                    onCancel={() => setModalVisible(false)}
                    onSuccess={handleStepFormSuccess}
                    step={currentStep}
                    taskId={taskId}
                    steps={steps}
                />
            </div>
        </Spin>
    );
};

export default StepList;
